package com.jesse.eclgy.plug.wrapper;


import com.jesse.eclgy.plug.util.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @Author: jesse
 * @Date: 2023/6/3 12:45
 */
public class DeleteWrapper implements IWrapper {

    Logger logger = LoggerFactory.getLogger(DeleteWrapper.class);

    private String tableName;

    private ConditionWrapper condition;

    public static DeleteWrapper builder()
    {
        return new DeleteWrapper();
    }


    /**
     * 查询表名
     */
    public DeleteWrapper tableName(String tableName)
    {
        this.tableName = tableName;
        return this;
    }

    public DeleteWrapper condition(Map<String, Object> conditionMap)
    {
        if (this.condition == null)
        {
            this.condition = ConditionWrapper.builder();
        }
        this.condition.condition(conditionMap);
        return this;
    }

    /*
     * 条件
     */
    public DeleteWrapper condition(ConditionWrapper condition)
    {
        this.condition = condition;
        return this;
    }

    public DeleteWrapper conditionEQ(String field, Object value)
    {
        this.condition = this.condition == null ? ConditionWrapper.builder() : this.condition.and();
        this.condition.eq(field, value);
        return this;
    }


    @Override
    public DeleteWrapper inject(Object obj)
    {
        this.tableName(ReflectionUtils.getTableName(obj.getClass(), false));
        this.condition(ReflectionUtils.getKeyField(obj));
        return this;

    }
    @Override
    public String getSql() {
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM ").append(this.tableName);
        if (null != this.condition && StringUtils.isNotBlank(this.condition.getSql())) {
            sql.append(" WHERE ").append(this.condition.getSql());
        } else {
            logger.warn("删除操作没有条件!!!");
        }
        return sql.toString();
    }

    @Override
    public List<Object> getParams()
    {
        return this.condition != null ? condition.getParams() : null;
    }
}
